//function+ajax+promise   封装get
/**
 * promise get封装
 * @param {string} url 请求地址
 * @param {object} params 请求参数
 * @param {onject} headers 请求头
 * @param {string} dataType 数据类型
 */
function get(url,params = {},headers={},dataType='json'){
    return new Promise((resolve,reject)=>{
        let xhr = new XMLHttpRequest
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4){
                if(xhr.status == 200){
                    let res = xhr.responseText
                    switch (dataType) {
                        case 'json':
                            res = JSON.parse(res)
                            console.log(res);
                            break;           
                        default:
                            break;
                    }
                    resolve(res)
                }else{
                    reject(xhr.status)
                }
            }
        }
        let temparr = []
        for (let key in params) {
            temparr.push(`${key}=${params[key]}`)
        }
        xhr.open('get',`${url}?${temparr.join('&')}`)
        for (const key in headers) {
            xhr.setRequestHeader(key,headers[key])
        }
        xhr.send(null)
    })
}

//function+ajax+promise   封装json
/**
 * promise post封装
 * @param {string} url 请求地址
 * @param {object} params 请求参数
 * @param {object} headers 请求头
 * @param {string} dataType 数据类型
 */
function json(url,params = {},headers={},dataType='json'){
    return new Promise((resolve,reject)=>{
        let xhr = new XMLHttpRequest
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4){
                if(xhr.status == 200){
                    let res = xhr.responseText
                    switch (dataType) {
                        case 'json':
                            res = JSON.parse(res)
                            break;                    
                        default:
                            break;
                    }
                    resolve(res)
                }else{
                    reject(xhr.status)
                }
            }
        }
        let temparr = []
        for (const key in params) {
            temparr.push(`${key}=${params[key]}`)
        }
        xhr.open('post',url)
        xhr.setRequestHeader('content-type','application/x-www-form-urlencoded')
        for (const key in headers) {
            xhr.setRequestHeader(key,headers[key])
        }
        xhr.send(`${temparr.join('&')}`)
    })
}